package com.season.seasonStudy.javase.j_016_dom4j;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

public class ReadXML {

    public static void setObject(Element ele, Object o) throws Exception {
        List<Element> list = ele.elements();
        if (list.size() != 0) {
            for (Element object : list) {
                Object parent = null;
                System.out.println("标签名：" + object.getName());
                if (object.attributeValue("class") != null) {
                    //if(parent==null){
                    parent = getObject(object.attributeValue("class"));
//                    ObjectUtil.setObject(o, object.getName(), parent);
                    //}
                    setObject(object, parent);
                } else
                    setObject(object, o);
            }
        }
        if (!ele.hasMixedContent()) {
            System.out.println("标签内容：" + ele.getTextTrim());
//            ObjectUtil.setObject(o, ele.getName(), ele.getTextTrim());
        }
    }

    public static void main(String[] args) throws Exception {
        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File("src/myxml.xml"));
        Element root = doc.getRootElement();
        Bookshop bs = new Bookshop();
        setObject(root, bs);
        System.out.println(bs.getName() + "," + bs.getBook().toString());
    }

    /**
     * 根据类名生成对象
     *
     * @param className
     * @return
     */
    private static Object getObject(String className) {
        try {
            Class<?> clazz = Class.forName(className);
            return clazz.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}

